//
//  BTELoginViewController.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/14.
//

import UIKit

class BTELoginViewController: BTEBaseViewController {
    
    fileprivate let server = BTELoginToolNetServer()
    
    var emotydate: Date?
    var logintime: Date?

    var v: BTELoginView {
        return view as! BTELoginView
    }
    
    override func loadView() {
        view = BTELoginView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        emotydate = Date()
        
        setNavigationBarHidden(true)
        
        actions()
        
        v.clicke = {[weak self] in
            self?.dismiss(animated: true)
        }
        
//        v.t1textfeild.text = "9953957981"
//        v.t2textfield.text = "241234"
    }
    
    
    private func actions(){
        v.loginButton.isUserInteractionEnabled = true
        let t = UITapGestureRecognizer.init(target: self, action: #selector(clickLogin))
        v.loginButton.addGestureRecognizer(t)
        
        v.t2getcodebutton.addTarget(self, action: #selector(clickgetcode), for: .touchUpInside)
        
        v.privicyView.didTapPrivacyLink = {[weak self] in
            self?.clicklink()
        }
        
        v.button.addTarget(self, action: #selector(clickvoice), for: .touchUpInside)
    }


    fileprivate func clicklink(){
        view.endEditing(true)
        let web = BTEWebViewViewController.init(url: "https://goolestan.com/SSW-WTO.html")
        navigationController?.pushViewController(web, animated: true)
    }
    
    @objc fileprivate func clickLogin(){
        view.endEditing(true)
        
        let tt = v.privicyView.checkboxButton.isSelected
        if !tt {
            BTEHUD.shared.showError(BTELanguageManager.shared.localizedString(forKey: "Please read and agree to the Privacy Agreement"), on: v)
            return
        }
        
        guard let te = v.t1textfeild.text,te.count > 0 else {
            BTEHUD.shared.showError(BTELanguageManager.shared.localizedString(forKey: "Please enter your mobile number"), on: v)
            return
        }
        
        guard let te2 = v.t2textfield.text,te.count > 0 else {
            BTEHUD.shared.showError(BTELanguageManager.shared.localizedString(forKey: "Please enter the verification code"), on: v)
            return
        }
        
        BTEHUD.shared.showLoader(on: view)
        server.geothermally(data: ["leucoxene":te,"belaud":te2]) {[weak self] result in
            switch result {
            case .success(let success):
                
                UserDefaults.standard.setValue((success?.sidelingwise?.upbows)!, forKey: USER_TOKEN)
                
                let dbg = self?.logintime == nil ? (self?.emotydate)! : (self?.logintime)!
                let t = TrackingEvent.init(step: "1", startTimestamp: "\(dbg.timeIntervalSince1970)", endTimestamp: "\(Date().timeIntervalSince1970)")
                BTELocationReporterManager.shared.reportLocation(for: t)
                
                NotificationCenter.default.post(name: .loginSuccess, object: nil)
                BTEHUD.shared.showSuccess(success!.squushy, on: (self?.view)!)
               
                self?.dismiss(animated: false)
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
        
    }
    
    @objc fileprivate func clickgetcode(){
        view.endEditing(true)
        
        guard let te = v.t1textfeild.text,te.count > 0 else {
            BTEHUD.shared.showError(BTELanguageManager.shared.localizedString(forKey: "Please enter your mobile number"), on: v)
            return
        }
        
        BTEHUD.shared.showLoader(on: view)
        server.qurshes(data: ["girls":te]) {[weak self] result in
            switch result {
            case .success(let success):
                self?.logintime = Date()
                BTEHUD.shared.showSuccess(success!.squushy, on: (self?.view)!)
                self?.startCountdown()
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
    }
    
    @objc fileprivate func clickvoice(){
        view.endEditing(true)
        
        guard let te = v.t1textfeild.text,te.count > 0 else {
            BTEHUD.shared.showError(BTELanguageManager.shared.localizedString(forKey: "Please enter your mobile number"), on: v)
            return
        }
        
        BTEHUD.shared.showLoader(on: view)
        server.Carneol(data: ["girls":te]) {[weak self] result in
            switch result {
            case .success(let success):
                self?.logintime = Date()
                BTEHUD.shared.showSuccess(success!.squushy, on: (self?.view)!)
                break
            case .failure(let failure):
                switch failure {
                case .Error(c: let b, m: let bd):
                    BTEHUD.shared.showError(bd, on: (self?.view)!)
                    break
                default:
                    break
                }
                break
            }
        }
 
    }
    
    

}



extension BTELoginViewController {
    
    
    func startCountdown() {
        v.t2getcodebutton.isEnabled = false
        v.remainingSeconds = v.totalCountdownSeconds
        updateButtonTitle()
        v.countdownTimer = Timer.scheduledTimer(
               timeInterval: 1.0,
               target: self,
               selector: #selector(updateCountdown),
               userInfo: nil,
               repeats: true
           )
       }
       
       @objc private func updateCountdown() {
           v.remainingSeconds -= 1
           
           if v.remainingSeconds <= 0 {
               // 倒计时结束
               invalidateTimer()
               resetButtonState()
           } else {
               // 更新按钮标题
               updateButtonTitle()
           }
       }
       
      func updateButtonTitle() {
          let title = "\(v.remainingSeconds)s"
          v.t2getcodebutton.setTitle(title: title)
       }
       
       func resetButtonState() {
           v.t2getcodebutton.isEnabled = true
           v.t2getcodebutton.setTitle(title: BTELanguageManager.shared.localizedString(forKey: "Get Code"))
       }
       
       func invalidateTimer() {
           v.countdownTimer?.invalidate()
           v.countdownTimer = nil
       }
    
}
